package com.lele.controller;


import com.lele.exception.DepartmentException;
import com.lele.pojo.Department;
import com.lele.service.IDepartmentService;
import com.lele.utils.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lele
 * @since 2022-11-26
 */
@RestController
@RequestMapping("/system/basic/department")
public class DepartmentController {
    @Resource
    private IDepartmentService departmentService;



    @GetMapping("/")
    public List<Department> getAllDepartment(){
        List<Department> departmentList=departmentService.getTreeDepartment();
        return departmentList;
    }


    /**
     * 添加部门，上级部门的id和新添加部门的部门名称
     *
     */
    @PostMapping("/")
    public Result insertDepartment(@RequestBody Department department){
        String name = department.getName();
        Integer parentId = department.getParentId();
        departmentService.insertDepartment(name,parentId);
        return Result.OK();
    }


    /**
     *       删除部门
     *       当该部门下拥有子节点时是不能够删除的
     */
    @DeleteMapping("{id}")
    public Result deleteDepartment(@PathVariable("id") Integer id){
        try {
            departmentService.deleteDepartment(id);
        } catch (DepartmentException e) {
            return Result.ERROR(e.getMessage());
        }
        return Result.OK();
    }
}
